<?php
declare (strict_types = 1);

namespace app\v1\controller;

use app\model\Address;
use think\Request;

class AddressController
{
	protected $middleware = ['Login' => ['except' =>['']]];
	
	/**
	 * 列表
	 * @param Request $request
	 */
	public function index(Request $request)
	{
		
		$rows=Address::where(['user_id'=>$request->user_id])
			->order(['id'=>'desc'])
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 新增地址
	 * @param Request $request
	 */
	function add(Request $request)
	{
		$params = $request->post();
		if ($params['default']==1){
			Address::where(['user_id'=>$request->user_id,'default'=>1])->update(['default'=>0]);
		}
		Address::create($params);
		writeJson();
	}
	
	
	/**
	 * 设置默认地址
	 * @param Request $request
	 */
	function setDefault(Request $request)
	{
		$id = $request->post('id/d');
		Address::where(['user_id'=>$request->user_id,'default'=>1])->update(['default'=>0]);
		Address::where(['id'=>$id])->update(['default'=>1]);
		writeJson();
	}
	
	
	/**
	 * 编辑
	 * @param Request $request
	 * @param int $id
	 */
	public function edit(Request $request,int $id)
	{

		$row = Address::find($id);
		if (!$request->isPost()){
			writeJson($row);
		}
		$params = $request->post();
		if ($params['default']==1){
			Address::where(['user_id'=>$request->user_id,'default'=>1])->update(['default'=>0]);
		}
		$row->save($params);
		writeJson();
	}

	
	/**
	 * 删除地址
	 */
	public function delete(Request $request)
	{
		$id = $request->post('id/d');
		Address::destroy($id);
		writeJson();
	}
	
	/**
	 * 获取默认地址
	 * @param Request $request
	 */
	function getDefault(Request $request)
	{
		$row = Address::where(['user_id'=>$request->user_id,'default'=>1])->find();
		writeJson($row);
	}
}
